package com.shop.loan.rentaldata;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.LoanOrderContractByMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.entity.*;
import com.shop.loan.model.enums.CompanyType;
import com.shop.loan.model.enums.ContractType;
import com.shop.loan.model.enums.ContractUserType;
import com.shop.loan.model.enums.PlatformType;
import com.shop.loan.model.vo.*;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.service.SettingService;
import com.shop.loan.util.LoanOrderUtil;
import com.shop.loan.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Component
public class RentalDataUtil {

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    LoanOrderContractByMybatisMapper loanOrderContractByMybatisMapper;

    @Resource
    SettingService settingService;

    @Resource
    LoanOrderUtil loanOrderUtil;

    @Resource
    RedisCache redisCache;

    @Value("${api.rental.apiKey}")
    private String apiKey;

    @Value("${api.rental.apiSecret}")
    private String apiSecret;

    @Value("${api.rental.url}")
    private String url;

    @Value("${sys.signature}")
    private String signature;

    @Value("${sys.urlByH5}")
    private String urlByH5;

    @Value("${sys.requestUrl}")
    private String requestUrl;

    @Value("${api.rental.oneKeyCode}")
    private String oneKeyCode;

    private static String nonce = "smzzxxjssmzzxxjs";

    /**
     * 查询余额
     *
     * @return
     */
    public BigDecimal getBalance() {
        String apiUrl = url + "/api/user/balance";
        JSONObject jsonObject = new JSONObject();
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getBalance】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getBigDecimal("data");
        }
        return null;
    }

    /**
     * 查询余额记录
     *
     * @return
     */
    public JSONObject getBalanceLog(Integer pageNum, Integer pageSize, Integer type) {
        String apiUrl = url + "/api/user/getBalanceLog";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum", pageNum);
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("type", type);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getBalanceLog】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }

    /**
     * ocr解析身份证
     *
     * @param ocrVo
     * @return
     */
    public JSONObject getOcrInfo(OcrVo ocrVo) {
        String apiUrl = url + "/api/ocr/get";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", ocrVo.getUrl());
        jsonObject.put("isFront", ocrVo.getIsFront());
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getOcrInfo】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    /**
     * 银行卡ocr
     *
     * @param imageUrl
     * @return
     */
    public JSONObject getOcrByBank(String imageUrl) {
        String apiUrl = url + "/api/ocr/getBank";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", imageUrl);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getOcrByBank】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    /**
     * 三要素比对
     *
     * @param
     * @return
     */
    public Boolean personVerifyMobile3(String realName, String idCardNo, String mobile) {
        String apiUrl = url + "/api/personVerifyMobile3";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("realName", realName);
        jsonObject.put("idCardNo", idCardNo);
        jsonObject.put("mobile", mobile);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【personVerifyMobile3】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
//        {"code":1,"data":{"result":1,"serialNo":"PV20220241202175954899744","type":"个人运营商三要素比对"},"msg":"成功"}

        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            if (resultJs.getJSONObject("data").getInteger("result") == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 银行卡三要素比对
     *
     * @param realName
     * @param idCardNo
     * @param bankCard
     * @return
     */
    public Boolean personalBank3(String realName, String idCardNo, String bankCard) {
        String apiUrl = url + "/api/personalBank3";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("realName", realName);
        jsonObject.put("idCardNo", idCardNo);
        jsonObject.put("bankCard", bankCard);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【personalBank3】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            if (resultJs.getJSONObject("data").getInteger("result") == 1) {
                return true;
            }
        }
        return false;
    }


    /**
     * 活体认证
     *
     * @param
     * @return
     */
    public JSONObject personAuthFace(String realName, String idCardNo, String mobile, String redirectUrl) {
        String apiUrl = url + "/api/personAuthFace";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("realName", realName);
        jsonObject.put("idCardNo", idCardNo);
        jsonObject.put("mobile", mobile);
        jsonObject.put("redirectUrl", redirectUrl);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【personAuthFace】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    /**
     * 活体认证成功处理
     *
     * @param serialNo
     * @return
     */
    public ResResult personAuthFaceSuccess(String serialNo) {
        String apiUrl = url + "/api/personAuthFaceSuccess";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("serialNo", serialNo);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【personAuthFaceSuccess】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS, resultJs.getString("data"));
        } else {
            return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
        }
    }


    /**
     * 获取人脸照片
     *
     * @param serialNo
     * @return
     */
    public JSONObject getFacePhoto(String serialNo) {
        String apiUrl = url + "/api/getFacePhoto";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("serialNo", serialNo);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getFacePhoto】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    /**
     * 天狼星
     *
     * @param name
     * @param mobile
     * @param idCardNum
     * @return
     */
    public String getTlxInfo(String name, String mobile, String idCardNum) {
        String apiUrl = url + "/api/report/get";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 100);//星耀
        jsonObject.put("name", name);
        jsonObject.put("mobile", mobile);
        jsonObject.put("idCardNum", idCardNum);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getTlxInfo】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getString("data");
            } else {
                return resultJs.getString("msg");
            }
        }
        return Code.REPORT_GET_FAIL.getMsg();
    }

    /**
     * 探针C
     *
     * @param name
     * @param mobile
     * @param idCardNum
     * @return
     */
    public String getTanZhenC(String name, String mobile, String idCardNum) {
        String apiUrl = url + "/api/report/get";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 109);//探针C
        jsonObject.put("name", name);
        jsonObject.put("mobile", mobile);
        jsonObject.put("idCardNum", idCardNum);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getTanZhenC】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getString("data");
            } else {
                return resultJs.getString("msg");
            }
        }
        return Code.REPORT_GET_FAIL.getMsg();
    }


    /**
     * 全景雷达
     *
     * @param name
     * @param mobile
     * @param idCardNum
     * @return
     */
    public String getRiskLeiDa(String name, String mobile, String idCardNum) {
        String apiUrl = url + "/api/report/get";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 110);//雷达
        jsonObject.put("name", name);
        jsonObject.put("mobile", mobile);
        jsonObject.put("idCardNum", idCardNum);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getRiskLeiDa】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getString("data");
            } else {
                return resultJs.getString("msg");
            }
        }
        return Code.REPORT_GET_FAIL.getMsg();
    }

    /**
     * 手动扣余额
     *
     * @return
     */
    @Async
    public String reportBalanceSub() {
        String apiUrl = url + "/api/report/balance/sub";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("typeList", "109,110");//雷达和探针
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【reportBalanceSub】 参数:{},返回:{}", jsonObject, result);
        return Code.REPORT_GET_FAIL.getMsg();
    }


    /**
     * 融担用户校验
     *
     * @param name
     * @param mobile
     * @param idCardNum
     * @return
     */
    public JSONObject getRdCheck(String name, String mobile, String idCardNum, String mobile1, String mobile2) {
        String apiUrl = url + "/api/rd/user/check";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("mobile", mobile);
        jsonObject.put("idCardNum", idCardNum);
        if (StringUtils.hasText(mobile1)) {
            jsonObject.put("mobile1", mobile1);
        }
        if (StringUtils.hasText(mobile2)) {
            jsonObject.put("mobile2", mobile2);
        }
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getRdCheck】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getJSONObject("data");
            }
        }
        return new JSONObject();
    }

    /**
     * 融担用户校验（MD5密文）
     *
     * @param mobile
     * @param idCardNum
     * @return
     */
    public JSONObject getRdCheckByMd5(String mobile, String idCardNum) {
        String apiUrl = url + "/api/rd/user/checkByMd5";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", mobile);
        jsonObject.put("idCardNum", idCardNum);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【getRdCheckByMd5】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getJSONObject("data");
            }
        }
        return new JSONObject();
    }


    /**
     * 订单上传到数据中心
     *
     * @param orderByMybatisList
     * @return
     */
    public ResResult orderPut(List<LoanOrderByMybatis> orderByMybatisList) {
        try {
            String apiUrl = url + "/api/order/put";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderList", orderByMybatisList);
            String result = HttpRequest.post(apiUrl)
                    .addHeaders(getHeadMap())
                    .body(jsonObject.toJSONString())
                    .execute().body();
            log.info("非凡数据【orderPut】 参数:{},返回:{}", jsonObject, result);
            JSONObject resultJs = JSON.parseObject(result);
            if (resultJs != null && resultJs.containsKey("code")) {
                if (resultJs.getInteger("code") == 1) {
                    return new ResResult(Code.SUCCESS, resultJs.getString("data"));
                } else {
                    return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return new ResResult(Code.FAIL);
    }

    /**
     * 逾期订单紧急联系人上传
     *
     * @param contactByMybatisList
     * @return
     */
    public ResResult overdueOrderContactPut(List<OverdueContactUploadVo> contactByMybatisList) {
        try {
            String apiUrl = url + "/api/order/overdue/contact/put";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("contactList", contactByMybatisList);
            String result = HttpRequest.post(apiUrl)
                    .addHeaders(getHeadMap())
                    .body(jsonObject.toJSONString())
                    .execute().body();
            log.info("非凡数据【overdueOrderContactPut】 参数:{},返回:{}", jsonObject, result);
            JSONObject resultJs = JSON.parseObject(result);
            if (resultJs != null && resultJs.containsKey("code")) {
                if (resultJs.getInteger("code") == 1) {
                    return new ResResult(Code.SUCCESS, resultJs.getString("data"));
                } else {
                    return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return new ResResult(Code.FAIL);
    }


    /**
     * 拒绝用户紧急联系人上传
     *
     * @param contactByMybatisList
     * @return
     */
    public ResResult rejectUserContactPut(List<OverdueContactUploadVo> contactByMybatisList) {
        try {
            String apiUrl = url + "/api/reject/user/contact/put";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("contactList", contactByMybatisList);
            String result = HttpRequest.post(apiUrl)
                    .addHeaders(getHeadMap())
                    .body(jsonObject.toJSONString())
                    .execute().body();
            log.info("非凡数据【rejectUserContactPut】 参数:{},返回:{}", jsonObject, result);
            JSONObject resultJs = JSON.parseObject(result);
            if (resultJs != null && resultJs.containsKey("code")) {
                if (resultJs.getInteger("code") == 1) {
                    return new ResResult(Code.SUCCESS, resultJs.getString("data"));
                } else {
                    return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return new ResResult(Code.FAIL);
    }

    /**
     * 上传黑名单
     */
    public Boolean blackPut(List<String> blackList) {
        try {
            String apiUrl = url + "/api/black/put";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("blackList", blackList);
            String result = HttpRequest.post(apiUrl)
                    .addHeaders(getHeadMap())
                    .body(jsonObject.toJSONString())
                    .execute().body();
            log.info("非凡数据【blackPut】 数量:{},返回:{}", blackList.size(), result);
            JSONObject resultJs = JSON.parseObject(result);
            if (resultJs != null && resultJs.containsKey("code")) {
                if (resultJs.getInteger("code") == 1) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return false;
    }

    /**
     * 上传拒绝用户
     *
     * @param userList
     * @return
     */
    public Boolean rejectUserPut(List<RejectUserPutVo> userList) {
        try {
            String apiUrl = url + "/api/reject/user/put";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userList", userList);
            String result = HttpRequest.post(apiUrl)
                    .addHeaders(getHeadMap())
                    .body(jsonObject.toJSONString())
                    .execute().body();
            log.info("非凡数据【blackPut】 数量:{},返回:{}", userList.size(), result);
            JSONObject resultJs = JSON.parseObject(result);
            if (resultJs != null && resultJs.containsKey("code")) {
                if (resultJs.getInteger("code") == 1) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return false;
    }


    /**
     * 创建签署合同
     *
     * @param orderId
     * @return
     */
    public ResResult createSignContract(Long orderId) {
        List<LoanOrderContractByMybatis> loanOrderContractByMybatisList = loanOrderContractByMybatisMapper.selectByOrderId(orderId, true);
        UserByMybatis userByMybatis = userByMybatisMapper.selectByOrderId(orderId);
        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(orderId);

//        CompanyByMybatis rdCompany = redisCache.getCompany(CompanyType.rd);
//        CompanyByMybatis loanCompany = redisCache.getCompany(CompanyType.loan);
//        if (rdCompany == null || !StringUtils.hasText(rdCompany.getASignAccount())) {
//            return new ResResult(Code.RD_COMPANY_NOT_EXIST);
//        }
//        if (loanCompany == null || !StringUtils.hasText(loanCompany.getASignAccount())) {
//            return new ResResult(Code.LOAN_COMPANY_NOT_EXIST);
//        }

        SettingByMybatis setting = settingService.getSetting();
        if (loanOrderContractByMybatisList == null || loanOrderContractByMybatisList.size() <= 0) {
            return new ResResult(Code.CONTRACT_FILE_NOT_EXIT);
        }

        ASignVo aSignVo = new ASignVo();
        aSignVo.setContractName("借款订单-" + orderId);
        if (PlatformType.app.getType().equals(loanOrderByMybatis.getFromClient())) {
            aSignVo.setRedirectUrl(requestUrl + "/success_1.html");
        } else {
            aSignVo.setRedirectUrl(urlByH5);
        }

        ASignerVo aSignerByUser = new ASignerVo();
        aSignerByUser.setAccount(userByMybatis.getMobile());
//        签约方式：
//        2：无感知签约（需要开通权限）
//        3：有感知签约
        aSignerByUser.setSignType(2);
        //人脸识别签约
        aSignerByUser.setValidateType(3);
        aSignerByUser.setMobile(userByMybatis.getMobile());
        //用户签章策略
        List<ASignStrategyVo> aSignStrategyByUserList = new ArrayList<>();
        //小贷公司签章策略
        List<ASignStrategyVo> aSignStrategyByLoanList = new ArrayList<>();
        //融担签章策略
        List<ASignStrategyVo> aSignStrategyByRdList = new ArrayList<>();

        List<ASignFileInfoVo> aSignFileInfoVoList = new ArrayList<>();
        for (int i = 0; i < loanOrderContractByMybatisList.size(); i++) {
            LoanOrderContractByMybatis loanOrderContractByMybatis = loanOrderContractByMybatisList.get(i);
            ASignFileInfoVo aSignFileInfoVo = new ASignFileInfoVo();
            aSignFileInfoVo.setFileurl(setting.getFileDomain() + loanOrderContractByMybatis.getUrl());
            aSignFileInfoVo.setFilename(loanOrderContractByMybatis.getName());
            aSignFileInfoVo.setExtension("docx");

            aSignFileInfoVoList.add(aSignFileInfoVo);

            if (loanOrderContractByMybatis.getType() == ContractType.loan.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.loan, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(200D);
//                    aSignStrategyVo2.setLocationMode(3);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }

                String loanSignKey = loanOrderUtil.getSignKey(ContractType.loan, ContractUserType.loan);
                if (StringUtils.hasText(loanSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(loanSignKey);
                    aSignStrategyVo2.setOffsetX(100D);
                    aSignStrategyByLoanList.add(aSignStrategyVo2);
                }

            } else if (loanOrderContractByMybatis.getType() == ContractType.loan_notify.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.loan_notify, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(200D);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }
            } else if (loanOrderContractByMybatis.getType() == ContractType.guarantee_contract.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.guarantee_contract, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(100D);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }

                String rdSignKey = loanOrderUtil.getSignKey(ContractType.guarantee_contract, ContractUserType.rd);
                if (StringUtils.hasText(rdSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(rdSignKey);
                    aSignStrategyVo2.setOffsetX(200D);
                    aSignStrategyByRdList.add(aSignStrategyVo2);
                }
            } else if (loanOrderContractByMybatis.getType() == ContractType.credit.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.credit, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(150D);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }
            } else if (loanOrderContractByMybatis.getType() == ContractType.guarantee_apply.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.guarantee_apply, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(100D);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }
            } else if (loanOrderContractByMybatis.getType() == ContractType.debenture_transfer.getType().intValue()) {
                String userSignKey = loanOrderUtil.getSignKey(ContractType.debenture_transfer, ContractUserType.user);
                if (StringUtils.hasText(userSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(userSignKey);
                    aSignStrategyVo2.setOffsetX(250D);
                    aSignStrategyByUserList.add(aSignStrategyVo2);
                }

                String loanSignKey = loanOrderUtil.getSignKey(ContractType.debenture_transfer, ContractUserType.loan);
                if (StringUtils.hasText(loanSignKey)) {
                    ASignStrategyVo aSignStrategyVo2 = new ASignStrategyVo();
                    aSignStrategyVo2.setAttachNo(i + 1);
                    aSignStrategyVo2.setSignKey(loanSignKey);
                    aSignStrategyVo2.setOffsetX(200D);
                    aSignStrategyByLoanList.add(aSignStrategyVo2);
                }
            }
        }
        //签署的文件
        aSignVo.setFileInfos(aSignFileInfoVoList);

        aSignerByUser.setStrategys(aSignStrategyByUserList);

        ASignerVo aSignerByLoan = new ASignerVo();
//        aSignerByLoan.setAccount(loanCompany.getASignAccount());
        aSignerByLoan.setSignType(2);
        aSignerByLoan.setStrategys(aSignStrategyByLoanList);

        ASignerVo aSignerByRd = new ASignerVo();
//        aSignerByRd.setAccount(rdCompany.getASignAccount());
        aSignerByRd.setSignType(2);
        aSignerByRd.setStrategys(aSignStrategyByRdList);


        List<ASignerVo> aSignerVoList = new ArrayList<>();
        aSignerVoList.add(aSignerByUser);
        aSignerVoList.add(aSignerByLoan);
        aSignerVoList.add(aSignerByRd);
        aSignVo.setSigners(aSignerVoList);

        String apiUrl = url + "/api//asign/createContract";
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(JSON.toJSONString(aSignVo))
                .execute().body();
        log.info("非凡数据【createSignContract】 参数:{},返回:{}", JSON.toJSONString(aSignVo), result);
        JSONObject resultJs = JSON.parseObject(result);
        String msg = Code.FAIL.getMsg();
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getJSONObject("data"));
            } else {
                msg = resultJs.getString("msg");
            }
        }
        return new ResResult(Code.FAIL.getCode(), msg, null);
    }

    public String removeUser(String mobile) {
        String apiUrl = url + "/api/removeUser";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", mobile);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("租机数据【removeUser】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getString("data");
            } else {
                return resultJs.getString("msg");
            }
        }
        return Code.REPORT_GET_FAIL.getMsg();
    }


    /**
     * 爱签添加个人用户
     *
     * @param mobile
     * @return
     */
    @Async
    public String addPersonalUserV2(String mobile, String name, String idCardNo) {
        String apiUrl = url + "/api/addPersonalUserV2";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", mobile);
        jsonObject.put("realName", name);
        jsonObject.put("idCardNo", idCardNo);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("租机数据【addPersonalUserV2】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return resultJs.getString("data");
            } else {
                return resultJs.getString("msg");
            }
        }
        return Code.REPORT_GET_FAIL.getMsg();
    }

//    /**
//     * 爱签 添加陌生用户
//     * @param mobile
//     * @param name
//     * @param idCardNo
//     * @return
//     */
//    @Async
//    public String addStrangerV2(String mobile, String name, String idCardNo) {
//        String apiUrl = url + "/api/addStrangerV2";
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("mobile", mobile);
//        jsonObject.put("realName", name);
//        jsonObject.put("idCardNo", idCardNo);
//        String result = HttpRequest.post(apiUrl)
//                .addHeaders(getHeadMap())
//                .body(jsonObject.toJSONString())
//                .execute().body();
//        log.info("租机数据【addStrangerV2】 参数:{},返回:{}", jsonObject, result);
//        JSONObject resultJs = JSON.parseObject(result);
//        if (resultJs != null && resultJs.containsKey("code")) {
//            if (resultJs.getInteger("code") == 1) {
//                return resultJs.getString("data");
//            } else {
//                return resultJs.getString("msg");
//            }
//        }
//        return Code.REPORT_GET_FAIL.getMsg();
//    }


    /**
     * 获取合同下载地址
     *
     * @param contractNo
     * @return
     */
    public ResResult downloadContract(String contractNo) {
        String apiUrl = url + "/api/asign/downloadContract";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("contractNo", contractNo);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("租机数据【downloadContract】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getJSONArray("data"));
            } else {
                return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
            }
        }
        return new ResResult(Code.FAIL);
    }

    /**
     * 预览合同
     *
     * @param contractNo
     * @return
     */
    public ResResult getContractInfo(String contractNo) {
        String apiUrl = url + "/api/asign/getContractInfo";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("contractNo", contractNo);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("租机数据【getContractInfo】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getJSONObject("data"));
            } else {
                return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
            }
        }
        return new ResResult(Code.FAIL);
    }


    /**
     * 按内容发送短信
     *
     * @param phone
     * @param content
     * @return
     */
    public Boolean sendByContent(String phone, String content) {
        String apiUrl = url + "/api/msg/sendByContent";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("signature", signature);
        jsonObject.put("phone", phone);
        jsonObject.put("content", content);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【sendByContent】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return true;
            }
        }
        return false;
    }


    /**
     * 一键登录获取手机号码（app）
     *
     * @param accessToken
     * @return
     */
    public ResResult loginByGetMobile(String accessToken) {
        String apiUrl = url + "/api/login/loginByGetMobile";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accessToken", accessToken);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【loginByGetMobile】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getString("data"));
            }
        }
        return new ResResult(Code.FAIL);
    }


    /**
     * 一键登录（获取授权token）
     *
     * @param oneKeyUrl
     * @param origin
     * @return
     */
    public ResResult loginByGetAuthToken(String oneKeyUrl, String origin) {
        String apiUrl = url + "/api/login/loginByGetAuthToken";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", oneKeyUrl);
        jsonObject.put("origin", origin);
        jsonObject.put("oneKeyCode", oneKeyCode);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【loginByGetAuthToken】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getString("data"));
            }
        }
        return new ResResult(Code.FAIL);
    }


    /**
     * 一键登录（h5获取手机号码）
     *
     * @param spToken
     * @return
     */
    public ResResult loginByGetPhoneWithToken(String spToken) {
        String apiUrl = url + "/api/login/loginByGetPhoneWithToken";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("spToken", spToken);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡数据【loginByGetPhoneWithToken】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code")) {
            if (resultJs.getInteger("code") == 1) {
                return new ResResult(Code.SUCCESS, resultJs.getString("data"));
            }
        }
        return new ResResult(Code.FAIL);
    }


    private Map getHeadMap() {
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(apiSecret, nonce, curTime);
        Map headMap = new HashMap();
        headMap.put("ApiKey", apiKey);
        headMap.put("Nonce", nonce);
        headMap.put("CurTime", curTime);
        headMap.put("CheckSum", checkSum);
        return headMap;
    }


}
